﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Diagnostics;

namespace MicroDal.SQLiteProviderTest
{
    [TestFixture]
    public class SessionTest
    {

        [TestFixtureSetUp]
        public void Setup()
        {
            try
            {
                using (var ses = new MicroDal.DataSession("sys"))
                {
                    ses.Execute("CREATE TABLE [test] ([id] INTEGER NOT NULL, [name] VARCHAR(50), [state] INTEGER);");
                    ses.Execute("INSERT INTO [test] VALUES (1, 'Jesper Jensen', @1)", /*State*/ null);
                    ses.Execute("INSERT INTO [test] VALUES (2, 'Jesper Jensen2', 1)");
                    ses.Execute("INSERT INTO [test] VALUES (3, @n, 1)", null);
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
            }
        }

        [TestFixtureTearDownAttribute]
        public void TearDown()
        {
            try
            {
                using (var ses = new MicroDal.DataSession("sys"))
                {
                    ses.Execute("DROP TABLE [test]");
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
            }
        }

        [Test]
        public void SimpleSelect()
        {
            using (var ses = new MicroDal.DataSession("sys"))
            {
                var name = ses.FetchOne("SELECT [name] FROM [test] WHERE id= @a;", r => r.GetString(0), 1);
                Debug.WriteLine(name);
                Assert.AreEqual("Jesper Jensen", name);
            }
        }

        [Test]
        public void SelectDbNullInt_0()
        {
            using (var ses = new MicroDal.DataSession("sys"))
            {
                var dto = ses.FetchOne("SELECT * FROM [Test] WHERE Id=1");
                Assert.AreEqual(0, dto.state);
            }
        }

        [Test]
        public void SelectDbNullVarchar_Null()
        {
            using (var ses = new MicroDal.DataSession("sys"))
            {
                var dto = ses.FetchOne("SELECT * FROM [Test] WHERE Id=3");
                Assert.IsNull(dto.name);
            }
        }

        [Test]
        public void ExecuteBackup()
        {
            var cstr = @"Data Source=|DataDirectory|\test_bu.db3;Pooling=true;FailIfMissing=false";

            using (var ses = new MicroDal.DataSession("sys"))
            {
                ses.Execute("BACKUP");

                using (var bu = new MicroDal.DataSession(cstr, "System.Data.SQLite"))
                {
                    var dto = bu.FetchOne("SELECT * FROM [Test] WHERE Id=1");
                    Assert.AreEqual(0, dto.state);
                    
                }
            }
        }
    }
}
